package com.sky.aspect;


import com.sky.annotation.AutoFill;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
public class AutoFillField {

    @Before("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    public void autoFillField(JoinPoint jp) throws Exception {
        Object entityObj = jp.getArgs()[0];

        Class<?> cls = entityObj.getClass();

        MethodSignature methodSignature = (MethodSignature) jp.getSignature();
        Method method = methodSignature.getMethod();
        AutoFill annotation = method.getAnnotation(AutoFill.class);


        if (annotation.value().equals(OperationType.INSERT)) {
            Method setCreateUser = cls.getDeclaredMethod("setCreateUser", Long.class);
            setCreateUser.invoke(entityObj, BaseContext.getCurrentId());
            Method setUpdateUser = cls.getDeclaredMethod("setUpdateUser", Long.class);
            setUpdateUser.invoke(entityObj, BaseContext.getCurrentId());
            Method setCreateTime = cls.getDeclaredMethod("setCreateTime", LocalDateTime.class);
            setCreateTime.invoke(entityObj, LocalDateTime.now());
            Method setUpdateTime = cls.getDeclaredMethod("setUpdateTime", LocalDateTime.class);
            setUpdateTime.invoke(entityObj, LocalDateTime.now());
        } else {
            Method setUpdateUser = cls.getDeclaredMethod("setUpdateUser", Long.class);
            setUpdateUser.invoke(entityObj, BaseContext.getCurrentId());
            Method setUpdateTime = cls.getDeclaredMethod("setUpdateTime", LocalDateTime.class);
            setUpdateTime.invoke(entityObj, LocalDateTime.now());
        }
    }

}
